package com.dgl.sdk.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import com.dgl.sdk.R;


import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;

public class PickPhoto {
	
	private static final int ACTIVITY_PICKLOCAL = 0;
	private static final int ACTIVITY_PICKCAMERA = 1;
	private static final int ACTIVITY_PICCUT = 2;
	
//	private String TMP_IMG = Environment.getExternalStorageDirectory() + "/tmpImg/" + "pickPhotoTemp.jpg";
	private Context context;
	private File imgFile;
	private String pickImgSavePath;
	private int widthRate = 0, hightRate = 0;
	private int outPutX = 0, outPutY = 0;
	private PickPhotoCallback pickPhotoCallback;
	
	private interface PickPhotoListener {
		public void pickphotoListener(int action);
	}
	
	public interface PickPhotoCallback {
		public void onStart();
		public void onComplete(Bitmap photo, File file);
	}
	
	public PickPhoto(Context context, String savePath){
		this.context  = context;
		pickImgSavePath = savePath;
	}
	
	public void setImgSavePath(String path){
		if(path != null){
			pickImgSavePath = path;
		}
	}
	
	public void pick(PickPhotoCallback callback){
		pickPhotoCallback = callback;
		pickPhotoCallback.onStart();
		pickImg();
	}
	
	
	private void pickImg(){
		imgFile = new File(pickImgSavePath);
		
		if(!imgFile.exists()){
			creatFile();
		}
		MyDialog dialog = new MyDialog(context, R.style.SDKConfirmDialog, new PickPhotoListener() {
			
			@Override
			public void pickphotoListener(int action) {
				if (action == ACTIVITY_PICKLOCAL) {
					Intent intent = new Intent(Intent.ACTION_PICK,
							MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
					((Activity) context).startActivityForResult(intent, ACTIVITY_PICKLOCAL);
				} else if (action == ACTIVITY_PICKCAMERA) {
					if (imgFile.exists()) {
						Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
						intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imgFile));
						((Activity) context).startActivityForResult(intent, ACTIVITY_PICKCAMERA);
					}
				}
			}
		});
		dialog.setOwnerActivity(((Activity) context));
		dialog.show();
		
	}
	
	private void creatFile() {
		if (!imgFile.getParentFile().exists())
			mkDir(imgFile);
		if (!imgFile.exists()) {
			try {
				imgFile.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	//递归创建文件夹
	private  void mkDir(File file) {
		if (file.getParentFile().exists()) {
			file.mkdir();
		} else {
			mkDir(file.getParentFile());
			file.mkdir();
		}
	}
	 
	
	public void setPickParam(int widthRate, int hightRate, int outPutX, int outPutY){
		this.widthRate = widthRate;
		this.hightRate = hightRate;
		this.outPutX = outPutX;
		this.outPutY = outPutY;
	}
	
	public File GetImageFile(){
		return imgFile;
	}
	
	public void Clear(){
		imgFile.delete();
	}
	

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == ((Activity) context).RESULT_OK) {
			switch (requestCode) {
			case ACTIVITY_PICKLOCAL:
				startPhotoZoom(data.getData());
				break;
			case ACTIVITY_PICKCAMERA:
				startPhotoZoom(Uri.fromFile(imgFile));
				break;
			case ACTIVITY_PICCUT:
				/**
				 * 非空判断大家一定要验证，如果不验证的话， 在剪裁之后如果发现不满意，要重新裁剪，丢弃
				 * 当前功能时，会报NullException，大家可以根据不同情况在合适的 地方做判断处理类似情况
				 * 
				 */
				if (data != null) {
					Bundle extras = data.getExtras();
					if (extras != null) {
						Bitmap photo = extras.getParcelable("data");
						
						Bitmap photoFinal;
						if((outPutX != 0)&&(outPutY != 0)){
							photoFinal = BitmapUtil.imageScale(photo, outPutX, outPutY);
						}else{
							photoFinal = photo;
						}
						
						try {
							FileOutputStream fos = new FileOutputStream(imgFile);
							photoFinal.compress(Bitmap.CompressFormat.PNG, 80, fos);
							fos.flush();
							fos.close();
						} catch (Exception e) {
							e.printStackTrace();
						}
						
						pickPhotoCallback.onComplete(photoFinal, imgFile);
					}
					
				}
				break;
			default:
				break;
			}
		}
	}

	/**
	 * 裁剪图片方法实现
	 * 
	 * @param uri
	 */
	public void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		if(widthRate != 0){
			intent.putExtra("aspectX", widthRate);
		}
		
		if(hightRate != 0){
			intent.putExtra("aspectY", hightRate);
		} 
		
		// outputX outputY 是裁剪图片宽高
		if(outPutX != 0){
			intent.putExtra("outputX", outPutX);
		}
		
		if(outPutY != 0){
			intent.putExtra("outputY", outPutY);
		}
		
		intent.putExtra("scaleUpIfNeeded", true);
		intent.putExtra("return-data", true);
		((Activity) context).startActivityForResult(intent, ACTIVITY_PICCUT);
	}

	/**
	 * 保存裁剪之后的图片数据
	 * 
	 * @param picdata
	 */
	private void setPicToView(Intent picdata) {
		Bundle extras = picdata.getExtras();
		if (extras != null) {
			Bitmap photo = extras.getParcelable("data");
			
//			Bitmap bitmap = BitmapUtil.imageScale(photo, 500, 500);
//			Bitmap bitmap = BitmapUtil.getRoundCornerBitmap(photo, 10.0f, 300, 300);
			try {
				FileOutputStream fos = new FileOutputStream(imgFile);
				photo.compress(Bitmap.CompressFormat.PNG, 100, fos);
				fos.flush();
				fos.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			Drawable drawable = new BitmapDrawable(photo);
//			userhead.setBackgroundDrawable(
//					BitmapUtil.zoomDrawable(drawable, userhead.getWidth(), userhead.getHeight()));
		}
	}
	
	
	public class MyDialog extends Dialog{
		Context context;
		PickPhotoListener pickPhoto;
		public static final int ACTIVITY_PICKLOCAL = 0;
		public static final int ACTIVITY_PICKCAMERA = 1;
		public MyDialog(Context context) {
			super(context);
			this.context = context;
		}

		public MyDialog(Context context, int theme,PickPhotoListener pickPhotoListener) {
			super(context, theme);
			this.context = context;
			this.pickPhoto=pickPhotoListener;
			setContentView(R.layout.pick_photo_dialog);
	        //set window params
	        Window window = getWindow();
	        WindowManager.LayoutParams params = window.getAttributes();
	        Resources resources = context.getResources();
	        DisplayMetrics dm = resources.getDisplayMetrics();
	        //set width,height by density and gravity
//	        params.width = dm.widthPixels;
	        params.height = LinearLayout.LayoutParams.WRAP_CONTENT;
	        params.width = LinearLayout.LayoutParams.WRAP_CONTENT;
	        params.gravity = Gravity.CENTER_HORIZONTAL;
	        window.setAttributes(params);
	      
	        setCanceledOnTouchOutside(true);
	        
	        SetOnClickListener();

		}

		protected void SetOnClickListener() {
	        Button cancel=(Button) findViewById(R.id.cancel);
	        Button camerapic=(Button) findViewById(R.id.camerapic);
	        Button choosepic=(Button) findViewById(R.id.choosepic);
	        cancel.setOnClickListener(new android.view.View.OnClickListener() {
				@Override
				public void onClick(View v) {
					dismiss();
				}		
			});
	        choosepic.setOnClickListener(new View.OnClickListener() {	
				@Override
				public void onClick(View v) {
					pickPhoto.pickphotoListener(ACTIVITY_PICKLOCAL);
					dismiss();
				}
			});
	        camerapic.setOnClickListener(new View.OnClickListener() {	
				@Override
				public void onClick(View v) {
					pickPhoto.pickphotoListener(ACTIVITY_PICKCAMERA);
					dismiss();
				}
			});
			
		}
	}
}
